package com.qingyun.web.controller.pcapi.shop;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.constant.UserConstants;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.domain.entity.SysRole;
import com.qingyun.common.core.domain.entity.SysUser;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.utils.StringUtils;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokProxy;
import com.qingyun.shop.domain.TiktokUserProxy;
import com.qingyun.shop.domain.TiktokUserShop;
import com.qingyun.shop.domain.bo.TiktokProxyBo;
import com.qingyun.shop.mapper.TiktokUserProxyMapper;
import com.qingyun.shop.mapper.TiktokUserShopMapper;
import com.qingyun.system.domain.ProxyUserRequest;
import com.qingyun.shop.domain.vo.TiktokProxyTreeVo;
import com.qingyun.shop.service.ITiktokProxyService;
import com.qingyun.system.service.ISysRoleService;
import com.qingyun.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Classname TikTokProxyUserController
 * @Author dyh
 * @Date 2021/9/10 15:27
 */
@Validated
@Api(value = "代理用户组织控制器", tags = {"^代理用户组织管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/system/proxy/user")
public class TikTokProxyUserController extends BaseController {

	private ITiktokProxyService tiktokProxyService;

	private ISysUserService userService;

	private ISysRoleService roleService;

	private TiktokUserProxyMapper tiktokUserProxyMapper;

	private TiktokUserShopMapper userShopMapper;

	/**
	 * 查询代理组织列表
	 */
	@ApiOperation("查询用户代理组织列表 system:proxy:user:treeList")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:treeList')")
	@GetMapping("/treelist")
	public AjaxResult<List<TiktokProxyTreeVo>> proxyTreelist(@Validated TiktokProxyBo bo) {
		List<TiktokProxyTreeVo> tiktokProxyVos = tiktokProxyService.queryPageList(bo);
		return AjaxResult.success(tiktokProxyVos);
	}

	@ApiOperation("查询代理商下的用户 system:proxy:user:userList")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:userList')")
	@GetMapping("/userList")
	public TableDataInfo<SysUser> proxyUser(ProxyUserRequest ProxyUserVo){
		TableDataInfo<SysUser> sysUserTableDataInfo = tiktokProxyService.selectPageUserList(ProxyUserVo);
		return sysUserTableDataInfo;
	}

	/**
	 * 添加代理商用户
	 * @return
	 */
	@ApiOperation("新增代理商用户 system:proxy:user:insert")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:insert')")
	@RepeatSubmit
	@PostMapping("/addProxyUser")
	public AjaxResult addProxyUser(@RequestBody SysUser user){
		if (SecurityUtils.getUser().getUserType().equals("02")) {
			return AjaxResult.error("商户角色不能创建代理");
		}
		if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
		{
			return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
		}
		else if (StringUtils.isNotEmpty(user.getPhonenumber())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
		{
			return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
		}
		else if (StringUtils.isNotEmpty(user.getEmail())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
		{
			return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}

		if (ObjectUtil.isNull(user.getProxyId())) {
			return AjaxResult.error("代理商不能为空");
		}

		SysRole role_key = roleService.lambdaQuery().eq(SysRole::getRoleKey, "proxy_role_key").one();
		user.setRoleIds(new Long[]{role_key.getRoleId()});

		user.setUserType(Constants.PROXY_USER);
		user.setCreateBy(getUsername());
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		boolean b = tiktokProxyService.insertProxyUserShop(user);
		return toAjax(b);
	}

	/**
	 * 查询代理用户信息
	 */
	@ApiOperation("查询代理商用户信息 system:proxy:user:query")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:query')")
	@GetMapping("/proxyUserinfo")
	public AjaxResult getInfo(Long userId){
		SysUser sysUser = userService.selectUserById(userId);
		if(ObjectUtil.isNotNull(sysUser)){
			TiktokProxy tiktokProxy = tiktokProxyService.selectProxyByUserId(userId);
			sysUser.setProxyId(tiktokProxy.getId());
		}
		return AjaxResult.success(sysUser);
	}


	/**
	 * 修改代理商用户
	 */
	@ApiOperation("修改代理商用户信息 system:proxy:user:edit")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:edit')")
	@PutMapping("/updateProxyUser")
    public AjaxResult updateProxyUserInfo(@Validated @RequestBody SysUser user){
		userService.checkUserAllowed(user);
		if (StringUtils.isNotEmpty(user.getPhonenumber())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
		{
			return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
		}
		else if (StringUtils.isNotEmpty(user.getEmail())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
		{
			return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setUpdateBy(getUsername());
		return toAjax(userService.updateUser(user));
	}


	/**
	 * 删除代理商用户
	 */
	@ApiOperation("删除代理商用户 system:proxy:user:delete")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:delete')")
	@DeleteMapping("/deleteProxyUser/{userIds}")
     public AjaxResult deletes(@PathVariable Long[] userIds){
		if (ArrayUtil.contains(userIds, getUserId()))
		{
			return error("当前用户不能删除");
		}
		int i = userService.deleteUserByIds(userIds);
		tiktokUserProxyMapper.delete(Wrappers.lambdaQuery(TiktokUserProxy.class).in(TiktokUserProxy::getUserId,userIds));
		userShopMapper.delete(Wrappers.lambdaQuery(TiktokUserShop.class).in(TiktokUserShop::getUserId,userIds));
		return toAjax(i);
	 }


	/**
	 * 重置密码
	 */
	@ApiOperation("修改代理下面用户密码 system:proxy:user:resetPwd")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:resetPwd')")
	@PutMapping("/resetPwd")
	public AjaxResult resetPwd(@RequestBody SysUser user)
	{
		userService.checkUserAllowed(user);
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		user.setUpdateBy(getUsername());
		return toAjax(userService.resetPwd(user));
	}

	/**
	 * 状态修改
	 */
	@ApiOperation("修改代理商用户状态 system:proxy:user:edit")
	@PreAuthorize("@ss.hasPermi('system:proxy:user:edit')")
	@PutMapping("/changeStatus")
	public AjaxResult changeStatus(@RequestBody SysUser user)
	{
		userService.checkUserAllowed(user);
		user.setUpdateBy(getUsername());
		return toAjax(userService.updateUserStatus(user));
	}



}
